// 导入db模块
const db = require('../common/db/index')
// 获取当前时间的函数
const { getCurrentTime } = require('../common/javascript/index')

// 定义消息类
class Message {
    //增
    add(sender_id, receiver_id, message_content) {
        let send_at = getCurrentTime();
        return new Promise((resolve, reject) => {
            db.query(`insert into pre_chat_messages(sender_id, receiver_id,message_content,send_at) values('${sender_id}','${receiver_id}','${message_content}','${send_at}')`)
                .then(
                    content => {
                        if (content.fieldCount === 0) {
                            resolve({
                                code: 200,
                                msg: "发送消息成功"
                            })
                        }
                    }
                )
        })
    }
    
    //查
    async list(user_id, friend_id) {
        let arr = [];
        await db.query(`select * from pre_chat_messages where sender_id='${user_id}' and receiver_id ='${friend_id}'`)
            .then(
                rows => {
                    arr.push(...rows)
                }
            )

        await db.query(`select * from pre_chat_messages where sender_id='${friend_id}' and receiver_id ='${user_id}'`)
            .then(
                rows => {
                    arr.push(...rows)
                }
            )

        arr.sort((prev, next) => {
            return prev.message_id - next.message_id
        })

        return new Promise((resolve, reject) => {
            resolve({
                code: 200,
                msg: "聊天记录",
                result: arr
            })
        })
    }

    // 删除
    remove(message_id){
        return new Promise((resolve, reject) => {
             db.query(`delete from pre_chat_messages where message_id = '${message_id}'`)
            .then(
                content => {
                    if(content.changedRows === 0){
                        resolve({
                            code: 200,
                            msg: "删除聊天记录"
                        })
                    }
                }
            )
        })
    }

    // 整合用户之间的聊天列表
    async items(user_id){
        let arr = [];
        let ids = []
        await db.query(`select * from pre_chat_messages where receiver_id='${user_id}'`)
        .then(
            rows=> {
                // console.log(rows);
                if(rows.length != 0) {
                    arr.push(...rows)
                }
            }
        )

        await db.query(`select * from pre_chat_messages where sender_id='${user_id}'`)
        .then(
            rows=> {
                // console.log(rows);
                if(rows.length != 0) {
                    arr.push(...rows)
                }
            }
        )

        // 筛选掉本人的信息，留下好友的信息
        for(let i = 0 ; i < arr.length ; i ++){
            let id = user_id == arr[i].sender_id ? arr[i].receiver_id : arr[i].sender_id;
            ids.push(id)
        }
        // console.log({ids})
        // console.log("2列表---",arr);
        // 处理异步编程比较不错的写法（方案）
        return new Promise((resolve,reject)=> {
            resolve({
                code: 200,
                msg: "聊天列表~~",
                result: [... new Set(ids)] 
            })
        })
    }
}

// 把消息类的实例挂在模块系统对象上
module.exports = Message;